package cn.kk.redis;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;

@Configuration
public class RedisConfig {
	//利用属性读取配置文件数据
	@Value("${spring.redis.nodes}")
	private String nodes;
	@Value("${spring.redis.pool.max-idle}")
	private Integer maxIdle;
	@Value("${spring.redis.pool.min-idle}")
	private Integer minIdle;
	@Value("${spring.redis.pool.max-total}")
	private Integer maxTotal;
	@Value("${spring.redis.pool.max-wait}")
	private Integer maxWait;

	//编写代码方法,将需要的内容这里成对象传递给分片池对象创建
	public JedisPoolConfig getConfig() {
		//利用属性,完成配置对象config的创建
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxIdle(maxIdle);
		config.setMinIdle(minIdle);
		config.setMaxTotal(maxTotal);
		config.setMaxWaitMillis(maxWait);
		return config;
	}
	
	//利用配置对象创建连接池对象
	//需要使用@Bean让框架管理,注入到该用到的位置使用
	@Bean
	public ShardedJedisPool getPool() {
		//整理节点信息
		List<JedisShardInfo> infolist = new ArrayList<JedisShardInfo>();
		//将节点信息解析成需要的内容,需要操作Spring的api
		String[] hosts = nodes.split(",");
		for (String hostAndPort : hosts) {
			String[] info = hostAndPort.split(":");
			JedisShardInfo jedisShardInfo = new JedisShardInfo(info[0],Integer.parseInt(info[1]));
			infolist.add(jedisShardInfo);
		}
		ShardedJedisPool pool = new ShardedJedisPool(getConfig(), infolist);
		return pool;
	}
	
	
	//连接哨兵操作主从高可用集群
	@Test
	public void sentinel(){
		//多个哨兵之间没有监控关系，顺序遍历，哪个能通就走哪个，不通，再检查下一个哨兵
    	Set<String> sentinels = new HashSet<String>();
    	sentinels.add(new HostAndPort("192.168.64.128",26379).toString());
    	sentinels.add(new HostAndPort("192.168.64.128",26380).toString());
    	sentinels.add(new HostAndPort("192.168.64.128",26381).toString());
    	
    	//mymaster是在sentinel.conf中配置的名称
    	//sentinel monitor mymaster 192.168.163.200 6380 1
    	JedisSentinelPool pool = new JedisSentinelPool("mymaster", sentinels);
    	System.out.println("当前master：" + pool.getCurrentHostMaster());
    	
    	Jedis jedis = pool.getResource();
		//jedis.auth("123456");
    	jedis.set("num", "1000");
    	System.out.println(jedis.get("num"));
    	pool.close();  
    	
    	pool.destroy();
    	System.out.println("ok");
}
}
